require(['./config'], () => {
   require(['header', 'template', 'fly'], (Header, template, fly) => {
      class DetailsPage {
         constructor() {
            //商品数量
            this.init()
            //name
            // console.log(Header.name)
            this.getIds().then(() => {
               this.changeColor()
               this.detailLeft()
               this.detailRight()
               this.magnifier()
               this.add()

               this.localContent()
            })
         }
         init() {
            //头部复用
            // new Header('/html/modules/header.html')
         }
         //获取传过来的id 通过get发请求
         getIds() {
            let id
            if(localStorage.getItem('id')){
               id = localStorage.getItem('id')
            }else{
               id = location.search.slice(4)
            }
            return new Promise(resolve => {
               // console.log(id)               
               $.get(`/product/skus?ids=${id}`, {
                  with_stock: true,
                  with_spu: true
               }, resp => {
                  if (resp.code === 0) {
                     console.log(resp)
                     const {
                        list
                     } = resp.data
                     console.log(list)
                     $('#buyShop').html(template('buyShopTemplate', {
                        list
                     }))
                     $('#pay').html(template('payTemplate', {
                        list
                     }))
                     $('#longImg').html(template('longImgTemplate', {
                        list
                     }))
                  }

                  resolve()
               })
            })

         }
        //改变颜色
        changeColor(){
           const _this = this
           $('.noA').on('click',function(){
              let id = $(this).data('id')
            //   location.href = `/html/detailsPage.html?id=${id}`
              localStorage.setItem('id',id)
              _this.getIds().then(() => {
               _this.changeColor()
               _this.detailLeft()
               _this.detailRight()
               _this.magnifier()
               _this.add()

               _this.localContent()
              }) 
           })
           $('#shopNum').on('click',()=>{
              location.href='/html/buyShop.html'
           })
        }
         //存储参数到localStrange
         localContent() {
            //点击添加按钮
            $('#goBuyShop').on('click', (e) => {
               //调用动画飞过去
               const name = Header.name
               if (Header.name) {
                  this.fly(e)
                  let local = {
                     name: name,
                     id: location.search.slice(4),
                     img: $('.bigImg').attr('src'),
                     title: $('#title').html(),
                     color: $('.color').html(),
                     price: parseInt($('#price').text().slice(1)).toFixed(2),
                     num: parseInt($('#num').val())
                  }
                  let cart = localStorage.getItem(`cart${name}`)
                  if (cart) {
                     //购物车已经有数据了
                     cart = JSON.parse(cart)
                     //继续判断购物车已有的数据是否包含当前数据
                     //如果包含当前数据数量++
                     //如果没有当前数据就push
                     const isExist = cart.some(shop => shop.id === local.id)
                     if (isExist) {
                        //当前商品已经加过购物车，数里加
                        cart = cart.map(shop => {
                           if (shop.id === local.id) {
                              shop.count += local.num
                           }
                           //不管加没加 都要return
                           return shop
                        })
                     } else {
                        cart.push({
                           ...local,
                           count: local.num,
                           check: true
                        })
                     }
                     localStorage.setItem(`cart${name}`, JSON.stringify(cart))
                  } else {
                     // 购物车为空，存当前数据，就算只存一条数据，也应该存数组，为了方便下一次继续存
                     // local.count = 1
                     // 初次加入购物车的时候让数据默认选中check: true
                     localStorage.setItem(`cart${name}`, JSON.stringify([{
                        ...local,
                        count: local.num,
                        check: true
                     }]))
                  }
                  console.log(local)
               } else {
                  alert('请先登录！')
               }
            })
         }
         //fly动画
         fly(e) {
            $(`<img class='fly' src="${$('.bigImg').attr('src')}">`).fly({
               start: {
                  left: e.clientX, //开始位置（必填）#fly元素会被设置成position: fixed
                  top: e.clientY, //开始位置（必填）
               },
               end: {
                  left: $('#shopNum').offset().left - $(window).scrollLeft(), //结束位置（必填）
                  top: $('#shopNum').offset().top - $(window).scrollTop(), //结束位置（必填）
                  //   width: 100, //结束时高度
                  //   height: 100, //结束时高度
               },
               // autoPlay: false, //是否直接运动,默认true
               speed: 0.7, //越大越快，默认1.2
               // vertex_Rtop：100, //运动轨迹最高点top值，默认20
               onEnd: function () {
                  // 这里的this指向当前的jquery对象
                  //清除这个fly对象
                  this.destroy()
                  //调用header里面的方法
                  //  new Header().calcCartCount()
                  Header.calcCartCount()
               } //结束回调
            })
         }
         //左边操作
         detailLeft() {
            $('.bigPic').children('img').eq(0).css('zIndex', '1')
            $('.bestPic').children('img').eq(0).css('zIndex', '1')
            $('.smallImg').on('click', function () {
               $(this).addClass('click').siblings().removeClass('click')
               let index = $(this).data('index')
               $('.bigPic').children('img').eq(index).css('zIndex', '1').siblings().css('zIndex', '0')
               $('.mask').css('zIndex', '2')
               $('.bestPic').children().eq(index).css('zIndex', '1').siblings().css('zIndex', '0')
            })
         }
         //右边操作
         detailRight() {
            let id
            if(localStorage.getItem('id')){
               id = localStorage.getItem('id')
            }else{
               id = location.search.slice(4)
            }
            // console.log(id)
            $('.btn').each(function (index, item) {
               if ($(this).data('id') == id) {
                  $(this).css('borderColor', '#6a8fe6')
               }
            })
         }
         add() {
            //商品数量
            this.count = 1
            $('#add').on('click', () => {
               if (this.count >= 10) {
                  alert('不要再点咯！你受不住的')
               } else {
                  $('#num').val(++this.count)
               }
               $('#count').html(this.count)
            })
            $('#sub').on('click', () => {
               if (this.count <= 1) {
                  $('#num').val(1)
                  // $('#sub').off()
               } else {
                  $('#num').val(--this.count)
               }
               $('#count').html(this.count)
            })

         }
         //放大镜
         magnifier() {
            //获取offset的值
            this.showInfo = {
               width: $('.bigPic').outerWidth(),
               height: $('.bigPic').outerHeight()
            }
            this.bestImgInfo = {
               width: $('.bestImg').outerWidth(),
               height: $('.bestImg').outerHeight()
            }
            this.maskInfo = {
               width: $('.mask').outerWidth(),
               height: $('.mask').outerHeight()
            }
            this.bigBoxInfo = {
               width: $('.bestPic').outerWidth(),
               height: $('.bestPic').outerHeight()
            }
            // console.log([this.maskInfo, this.bestImgInfo, this.showInfo])
            //重新设置bigBox的大小
            /* 
            mask / show = bigBox / bigImg
            */
            this.bigBoxInfo.width = parseInt(this.maskInfo.width * this.bestImgInfo.width / this.showInfo.width)
            this.bigBoxInfo.height = parseInt(this.maskInfo.height * this.bestImgInfo.height / this.showInfo.height)
            $('.bestPic').css({
               width: this.bigBoxInfo.width,
               height: this.bigBoxInfo.height
            })
                                                        
            //移动mask 在bigImg在bigBox中移动
            $('.bigPic').on('mousemove', (e) => {
               //计算left值和top值
               let _left = e.pageX - $('.left')[0].offsetLeft - $('.bigPic')[0].offsetLeft - ($('.mask')[0].offsetWidth / 2),
                  _top = e.pageY - $('.left')[0].offsetTop - $('.bigPic')[0].offsetTop - ($('.mask')[0].offsetHeight / 2)
               // console.log(_left, _top)
               if (_left <= 0) {
                  _left = 0
               }
               if (_left >= this.showInfo.width - this.maskInfo.width) {
                  _left = this.showInfo.width - this.maskInfo.width
               }
               if (_top <= 0) {
                  _top = 0
               }
               if (_top >= this.showInfo.height - this.maskInfo.height) {
                  _top = this.showInfo.height - this.maskInfo.height
               }
               $('.mask').css({
                  left: _left,
                  top: _top
               })
               //改变bigImg的left和top值 负的
               /* 
                  mask移动的距离 / mask最大的移动距离 = bigIm移动的距离 / bigIm最大的移动距离  
               */
               let moveLeft = _left * (this.bestImgInfo.width - this.bigBoxInfo.width) / (this.showInfo.width - this.maskInfo.width)
               let moveTop = _top * (this.bestImgInfo.height - this.bigBoxInfo.height) / (this.showInfo.height - this.maskInfo.height)

               $('.bestImg').css({
                  left: -moveLeft,
                  top: -moveTop
               })
            })

            //显示隐藏mask和大图
            $('.bigPic').on('mouseenter', () => {
               $('.mask').css('display', 'block')
               $('.bestPic').css('display', 'block')
            })
            $('.bigPic').on('mouseleave', () => {
               $('.mask').css('display', 'none')
               $('.bestPic').css('display', 'none')
            })
         }


      }
      new DetailsPage()
   })
})